include([],

function() {

	declare('controller.AnalogStick');
	
	AnalogStick = function(hitregion){
		this.touchID = -1;
		this.touchPos = new Vector2(0,0);
		this.touchStartPos = new Vector2(0,0);
		this.input = new Vector2(0,0);
		this.hitregion = hitregion;
		this.listeners = [];
		
		this.size = 20;
	}
	
	AnalogStick.prototype = {
		inputChanged : function(){
			var input = this.input;
			iterate(this.listeners, function(callback){
				callback(input);
			});
		},	
		addListener : function(callback){
			this.listeners.push(callback);
		},
		draw : function(context2d){
			var c = context2d;
	
			if(this.touchID>=0){
				c.beginPath(); 
				c.strokeStyle = "cyan"; 
				c.lineWidth = 6; 
				c.arc(this.touchStartPos.x, this.touchStartPos.y, this.size,0,Math.PI*2,true); 
				c.stroke();
				c.beginPath(); 
				c.strokeStyle = "cyan"; 
				c.lineWidth = 2; 
				c.arc(this.touchStartPos.x, this.touchStartPos.y, this.size / 4,0,Math.PI*2,true); 
				c.stroke();
				c.beginPath(); 
				c.strokeStyle = "cyan"; 
				c.arc(this.touchPos.x, this.touchPos.y, this.size, 0,Math.PI*2, true); 
				c.stroke(); 
			}
		},
		onButtonDown : function(e) {
			if((this.touchID<0) && this.hitregion.intersects(e))
			{
				this.touchID = e.bId.id; 
				this.touchStartPos.reset(e.x, e.y); 	
				this.touchPos.copyFrom(this.touchStartPos); 
				this.input.reset(0,0);
				this.inputChanged();
			}
		},
		onMove : function (e) {
			if(e.bId && this.touchID == e.bId.id)
			{
				this.touchPos.reset(e.x, e.y); 
				this.input.copyFrom(this.touchPos); 
				this.input.minusEq(this.touchStartPos);
				this.inputChanged();
			}
		}, 
		onButtonUp : function (e) { 
			if(e.bId && this.touchID == e.bId.id)
			{
				this.touchID = -1; 
				this.input.reset(0,0);
				this.inputChanged();
			}		
		}
	}
});